package com.demo.servlet.demo1216;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/demo1216/upload01.do")
public class FileUpload01Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断上传的数据是否为多段表单数据 multipart/form-data （只有是多段表单数据 才是文件上传）
        if (ServletFileUpload.isMultipartContent(request)) {
            //FileItemFactory 工厂实现类创建
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

            //开始解析上传数据 获取每一个上传的表单项
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);
                //对每一项 FileItem 进行循环判断，是普通类型还是文件类型
                for (int i = 0; i < list.size(); i++) {
                    FileItem fileItem = list.get(i);
                    if (fileItem.isFormField()) {
                        //普通表单项
                        System.out.println("表单项的 name = " + fileItem.getFieldName());
                        System.out.println("表单项的 value = " + fileItem.getString("UTF-8"));
                    } else {
                        System.out.println("表单项的 name = " + fileItem.getFieldName());
                        System.out.println("上传的文件名 = " + fileItem.getName());
                        fileItem.write(new File("D:\\imgUpload\\" + fileItem.getName()));
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
